// pages/payment/payment.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartItems: [],
    totalPrice: 0,
    address: null,
    paymentMethods: [
      { id: 1, name: '微信支付', icon: 'wechat' },
      { id: 2, name: '支付宝', icon: 'alipay' },
      { id: 3, name: '银行卡', icon: 'card' }
    ],
    selectedPaymentMethod: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 从本地存储获取订单信息
    const currentOrder = wx.getStorageSync('currentOrder') || [];
    
    if (currentOrder.length === 0) {
      wx.showToast({
        title: '订单信息错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }

    // 转换订单数据格式
    const cartItems = currentOrder.map(item => ({
      id: item.skuId || item.id,
      name: item.title,
      price: parseFloat(item.price),
      quantity: item.num || item.quantity,
      image: item.cover || item.banner[0],
      spec: item.sku || item.spec
    }));

    // 计算总价
    let totalPrice = 0;
    cartItems.forEach(item => {
      totalPrice += item.price * item.quantity;
    });

    this.setData({
      cartItems,
      totalPrice: totalPrice.toFixed(2)
    });
  },

  // 选择支付方式
  selectPaymentMethod(e) {
    const methodId = e.currentTarget.dataset.id;
    this.setData({
      selectedPaymentMethod: methodId
    });
  },

  // 提交支付
  submitPayment() {
    if (!this.data.address) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none'
      });
      return;
    }

    // 模拟支付请求
    wx.showLoading({
      title: '支付中...'
    });

    // 这里应该调用后端支付接口
    setTimeout(() => {
      wx.hideLoading();
      
      // 生成订单号
      const orderNo = 'ORDER' + Date.now();
      
      // 保存订单信息
      const orderInfo = {
        orderNo: orderNo,
        items: this.data.cartItems,
        totalPrice: this.data.totalPrice,
        address: this.data.address,
        paymentMethod: this.data.selectedPaymentMethod,
        status: 'paid',
        createTime: new Date().toISOString()
      };

      // 获取现有订单列表
      let orderList = wx.getStorageSync('orderList') || [];
      orderList.unshift(orderInfo);
      wx.setStorageSync('orderList', orderList);

      // 如果是购物车结算，清空购物车中已购买的商品
      const currentOrder = wx.getStorageSync('currentOrder') || [];
      if (currentOrder.length > 0) {
        let cartList = wx.getStorageSync('cart') || [];
        currentOrder.forEach(orderItem => {
          cartList = cartList.filter(cartItem => 
            !(cartItem.id === orderItem.id && cartItem.spec === orderItem.spec)
          );
        });
        wx.setStorageSync('cart', cartList);
      }

      // 清空当前订单
      wx.removeStorageSync('currentOrder');
      
      // 跳转到支付成功页
      wx.redirectTo({
        url: `/pages/paymentSuccess/paymentSuccess?orderNo=${orderNo}`
      });
    }, 1500);
  },

  // 选择地址
  selectAddress() {
    wx.navigateTo({
      url: '/pages/address/addressList'
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const address = wx.getStorageSync('selectedAddress');
    if (address) {
      this.setData({ address });
    }
    // 其他初始化...
  },
  selectAddress() {
    wx.navigateTo({
      url: '/pages/address/address'
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
});